<template>
  <div class="h-full w-full flex absolute inset-0 bg-[#fff] rounded-[0.5rem]">
    <div class="w-[17.5rem] mr-4">
      <div class="py-1.5 pl-4">
        <a-button type="link" class="back" @click="handleBack">
          <template #icon>
            <LeftOutlined />
          </template>
          <span>返回</span>
        </a-button>
      </div>
      <div class="pl-4 overflow-y-scroll h-[calc(100%-3rem)]">
        <Tree ref="treeRef" :search="false" @updateCurrent="updateCurrent" />
      </div>
    </div>
    <div class="flex-1">
      <div class="py-1.5">
        <a-button class="ghost" @click="openMarkModal('upload')">
          上传无人机数据
        </a-button>
        <!-- <a-button type="primary" ghost class="ml-4">标定</a-button> -->
      </div>
      <div class="h-[calc(100%-3.125rem)] image">
        <a-spin :spinning="loading" tip="正在加载..." class="image-loading" />
        <!-- <a-image
          v-if="imgUrl"
          height="100%"
          width="100%"
          :preview="false"
          :src="imgUrl"
        /> -->
        <canvas id="canvasDrawRect"></canvas>
      </div>
    </div>
    <div class="w-[14.5rem] ml-4 pr-4">
      <div class="py-1.5 font-[700] text-[0.875rem]">
        <a-button class="sub">标定设备列表</a-button>
      </div>
      <div class="h-[calc(100%-4rem)] overflow-y-auto uav">
        <a-table
          :pagination="false"
          :columns="columns"
          :data-source="sourceData"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'name'">
              <span class="dot" :title="record.deviceName">
                {{ record.deviceName }}
              </span>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-button
                type="link"
                class="delete"
                @click="openMarkModal('delete', record)"
              >
                删除
              </a-button>
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </div>

  <IndexMarkModal
    ref="indexMarkModalRef"
    :selectList="devList"
    @confirm="handleConfirm"
    @cancel="initDraw"
    @init="initThree"
  />
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, nextTick } from 'vue'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

import Tree from '@/components/tree/UavTree.vue'
import IndexMarkModal from './IndexMarkModal.vue'
import { getImgUrl, getDevList, getUavDevList, draw } from './serve.api'

const emit = defineEmits(['initData'])
const handleBack = () => emit('initData')

const loading = ref(false)

const devList = ref([])
const sourceData = ref([])

const canvasCtx = ref()
const canvasObj = reactive({
  width: 0,
  height: 0,
  pX: 0,
  pY: 0,
  labelId: '',
  algSeqName: '',
  deviceId: '',
  deviceName: '',
  widthRatio: 0,
  heightRatio: 0
})

const columns = [
  {
    title: '设备名称',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: '5rem'
  }
]

// 上传/删除
type ModalType = 'upload' | 'delete' | 'add'
const indexMarkModalRef = ref()

const openMarkModal = (type: ModalType, item?: any) => {
  indexMarkModalRef.value.showModal(type, item)
}

async function getImageUrl(item: any) {
  loading.value = true
  try {
    console.log('选中节点', item)
    canvasObj.labelId = item.id
    loading.value = false

    initDraw()
  } catch (error) {
    console.error(error)
  }
}

// 选中树节点时获取图片
const isFirst = ref(true)
const treeRef = ref()
const updateCurrent = (item: any) => {
  if (isFirst.value) {
    getImageUrl(item?.children[0]?.children[0])
    isFirst.value = false
  } else {
    if (item.children.length !== 0) return
    getImageUrl(item)
  }
}

function initThree() {
  treeRef.value.initTreeFun()
}

// 确定
async function handleConfirm(data: any) {
  canvasObj.algSeqName = data.algSeqName
  canvasObj.deviceId = data.deviceId
  canvasObj.deviceName = data.deviceName

  try {
    draw({
      labelId: canvasObj.labelId,
      deviceId: canvasObj.deviceId,
      deviceName: canvasObj.deviceName,
      algSeqName: canvasObj.algSeqName,
      deviceLocation: `${canvasObj.pX},${canvasObj.pY}`
    })
    initDraw()
    message.success('标定成功')
  } catch (error) {
    console.error(error)
  }
}

// 初始化绘制标定
function initDraw() {
  getImgUrl({ id: canvasObj.labelId }).then((res) => {
    const image = new Image()
    image.src = res
    image.setAttribute('crossOrigin', 'Anonymous')
    console.log(res, '图片地址')
    image.onload = function () {
      console.log(image.width, image.height, '图片原始宽高')

      const displayWidth = canvasObj.width // 压缩后显示的宽度
      const displayHeight = canvasObj.height // 压缩后显示的高度

      const widthRatio = image.width / displayWidth
      const heightRatio = image.height / displayHeight

      console.log(widthRatio, heightRatio, '宽高比')
      canvasObj.widthRatio = widthRatio
      canvasObj.heightRatio = heightRatio

      // const width = canvasObj.width
      // const height = canvasObj.height

      // canvasCtx.value.drawImage(image, 0, 0, width, height)
      canvasCtx.value.drawImage(image, 0, 0, displayWidth, displayHeight)

      // 绘制标定点
      getUavDevList({ labelId: canvasObj.labelId }).then((res) => {
        sourceData.value = res
        nextTick(() => {
          if (res) {
            res.forEach((ele: any) => {
              const points = ele.deviceLocation.split(',')
              const x = points[0] / canvasObj.widthRatio
              const y = points[1] / canvasObj.heightRatio

              drawPoint(x, y) // 绘制点
              drawText(ele.deviceName, x, y) // 绘制文字
            })
          }
        })
      })

      requestAnimationFrame(() => {}) // 在所有绘制操作完成后请求帧
    }
  })
}

// 绘制点
function drawPoint(x: number, y: number) {
  // 7 半径
  // const radius = 7 / Math.max(canvasObj.widthRatio, canvasObj.heightRatio)

  canvasCtx.value.save()

  canvasCtx.value.beginPath()
  canvasCtx.value.arc(x, y, 7, 0, 2 * Math.PI)
  canvasCtx.value.fillStyle = '#ff0000'
  canvasCtx.value.fill()

  canvasCtx.value.restore()
}

// 绘制文字
function drawText(value: string, x: number, y: number) {
  const { width } = canvasCtx.value.measureText(value)

  canvasCtx.value.font = '1rem MicrosoftYaHei Arial'
  canvasCtx.value.fillStyle = '#ff0000'

  let textX = 0
  let textY = 0

  if (x < 100) {
    textX = x
  } else if (x > canvasObj.width - 100) {
    textX = x - width
  } else {
    textX = x - width / 2
  }

  if (y < 100) {
    textY = y + 26
  } else {
    textY = y - 16
  }

  canvasCtx.value.fillText(value, textX, textY)
}

onMounted(() => {
  const canvas = document.getElementById('canvasDrawRect') as HTMLCanvasElement
  if (canvas) {
    canvasCtx.value = canvas.getContext('2d')
    const imageD = document.getElementsByClassName('image')[0]
    const { clientWidth, clientHeight } = imageD
    canvas.width = clientWidth
    canvas.height = clientHeight
    canvasObj.width = clientWidth
    canvasObj.height = clientHeight

    // TODO 点击画布绘制点
    // canvas.onclick = function (event) {
    //   const rect = canvas.getBoundingClientRect()
    //   const x = event.clientX - rect.left
    //   const y = event.clientY - rect.top

    //   canvasObj.pX = x
    //   canvasObj.pY = y
    //   drawPoint(x, y)
    //   openMarkModal('add')
    // }

    // TODO 鼠标按下画布绘制点
    canvas.addEventListener('mousedown', function (event) {
      // console.log(event)

      const rect = canvas.getBoundingClientRect()
      // console.log(rect, 'rect')

      const x = (event.clientX - rect.left) * canvasObj.widthRatio
      const y = (event.clientY - rect.top) * canvasObj.heightRatio
      console.log('原始图片上的点坐标:', x, y)

      canvasObj.pX = x
      canvasObj.pY = y
      drawPoint(x / canvasObj.widthRatio, y / canvasObj.heightRatio)
      openMarkModal('add')
    })
  }

  getDevList().then((res) => {
    devList.value = res
  })
})

function transferData() {
  console.log('进入标定页面')

  // console.log(type, row);
  // state.form.id = row.id;
  // if (row && row.id) {
  //   getDetail(row.id);
  // }
}

defineExpose({ transferData })
</script>

<style lang="less" scoped>
.back {
  display: flex;
  align-items: center;

  span {
    margin-left: 0.125rem;
    font-size: 0.875rem;
    text-decoration: none;
    color: #86909c;
    font-weight: 700;
  }

  &:hover span {
    color: #00796a;
  }
}

.image {
  position: relative;
  width: 100%;
  height: calc(100% - 3.125rem);

  &-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: block;
  }

  .ant-image {
    width: 100%;
    height: 100%;
  }
}

/deep/.uav {
  .ant-table-container table > thead > tr:first-child th:first-child {
    padding: 0;
    text-align: center;
  }

  .ant-table-tbody > tr > td:first-child {
    padding: 0 0 0 1.458rem;
  }

  .ant-table-container table > thead > tr:first-child th:last-child {
    padding: 0;
    text-align: center;
  }

  .ant-table-tbody > tr > td:last-child {
    padding: 0;
    text-align: center;
  }

  .dot {
    position: relative;
    display: flex;
    align-items: center;

    &::before {
      position: absolute;
      left: -0.8rem;
      display: inline-block;
      width: 0.5rem;
      height: 0.5rem;
      background-color: #f00;
      border-radius: 50%;
      content: '';
    }
  }
}
</style>
